package com.jeesite.modules.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.utils.CommonPath;


public class TTest {
	  public static void main(String[] args) {
		  /*try{
			URL url = new URL("http://thirdwx.qlogo.cn/mmopen/vi_32/Vegkzdr6BavmvYqksJw5EfoOueQnia17Rmgv4h9etC4fVOf2tXjXPs3gGqYLicotTpUwic2AmqJEvUT4DzRTayx8w/132");
			DataInputStream dataInputStream = new DataInputStream(url.openStream());
			// 微信头像专门放置点
			String filePath = "D:\\bc\\";
			//服务端路径和图片名称
			String imageName = filePath + "dd.png";
			// 检查文件夹是否存在
			File checkFolder = new File(
					filePath);
			if (!checkFolder.exists()) {
				checkFolder.mkdir();
			}
			FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
			ByteArrayOutputStream output = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024];
			int length;

			while ((length = dataInputStream.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}
			fileOutputStream.write(output.toByteArray());
			dataInputStream.close();
			fileOutputStream.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}*/

	/*	 try{
		CloseableHttpClient  httpClient = HttpClientBuilder.create().build();
		  HttpPost httpPost = new HttpPost("http://thirdwx.qlogo.cn/mmopen/vi_32/Vegkzdr6BavmvYqksJw5EfoOueQnia17Rmgv4h9etC4fVOf2tXjXPs3gGqYLicotTpUwic2AmqJEvUT4DzRTayx8w/132");
         // httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
         
          StringEntity entity;
        
          entity = new StringEntity("");
          entity.setContentType("image/png");

          httpPost.setEntity(entity);
          HttpResponse response;

          response = httpClient.execute(httpPost);
          InputStream inputStream = response.getEntity().getContent();
          
         
  		String path="D:\\bc";
  		String deshPath="D:\\bc\\d.png";
  		System.out.println("---------------0001111===="+"D:\\bc\\d.png");

          File targetFile = new File(path);  
          if(!targetFile.exists()){    
              targetFile.mkdirs();    
          }       
          FileOutputStream out = new FileOutputStream(deshPath);

          byte[] buffer = new byte[1024];
          int bytesRead = 0;
          while((bytesRead = inputStream.read(buffer, 0, 1024)) != -1) {
              out.write(buffer, 0, bytesRead);
          }

          out.flush();
          out.close();
		 }catch(Exception ex){}*/
		 /* try {
			getQcodeImg(null, "xxx", "pages/goodDel/goodDel");//page/goodDel/goodDel
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		String name=  replaceNameX("刘昆");
		System.out.println(name);
	}
	
	  public static String getQcodeImg(HttpServletRequest request,String sceneStr,String page) throws Exception {
	        //获取token
		 String path = request.getSession().getServletContext().getRealPath("")
  				+ CommonPath.getDestFolder(request) + "/";
		 // String path="D:\\bc\\";
		
          String fileName = UUID.randomUUID().toString() + ".png";
  		String deshPath=path+fileName;
  		
	        String result1 = get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx819630a1fe8a51fb&secret=9addae533648463ebeacc1013fb64980");
	      //  String result1 = get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb0283c0ffa73cd90&secret=4493a55897cda0b79dbac61651d24e5d");
	        String access_token = JSONObject.parseObject(result1).getString("access_token");
	        
	        if(StringUtils.isNotBlank(access_token)) {
	           
	            Map<String, Object> params = new HashMap<>();
	            params.put("scene", sceneStr);
	            params.put("page", page);
	            params.put("width", 430);
	           
	            params.put("auto_color", false);
	            params.put("is_hyaline", false);
	            Map<String,Object> line_color = new HashMap<>();
	            line_color.put("r", 0);
	            line_color.put("g", 0);
	            line_color.put("b", 0);
	            params.put("line_color", line_color);

	            CloseableHttpClient  httpClient = HttpClientBuilder.create().build();

	            HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token);
	            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
	            String body = JSON.toJSONString(params);
	            StringEntity entity;
	            entity = new StringEntity(body);
	            entity.setContentType("image/png");

	            httpPost.setEntity(entity);
	            HttpResponse response;

	            response = httpClient.execute(httpPost);
	            InputStream inputStream = response.getEntity().getContent();
	          

	            File targetFile = new File(path);  
	            if(!targetFile.exists()){    
	                targetFile.mkdirs();    
	            }       
	            FileOutputStream out = new FileOutputStream(deshPath);

	            byte[] buffer = new byte[1024];
	            int bytesRead = 0;
	            while((bytesRead = inputStream.read(buffer, 0, 1024)) != -1) {
	                out.write(buffer, 0, bytesRead);
	            }

	            out.flush();
	            out.close();
	        } else {
	         //  System.out.println("获取access_token错误");
	        }
	        return deshPath;
	    }

	    /**
	     * 发送get请求
	     * @param url
	     * @return
	     */
	    public static String get(String url) {
	        RestTemplate restTemplate = new RestTemplate();
	        HttpHeaders headers = new HttpHeaders();
	        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
	        HttpEntity<String> entity = new HttpEntity<String>(url, headers);
	        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
	        return responseEntity.getBody();
	    }
	    
	    public static Map getminiqrQr(String sceneStr, String accessToken) {
	        RestTemplate rest = new RestTemplate();
	        InputStream inputStream = null;
	        OutputStream outputStream = null;
	        try {
	            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
	            Map<String,Object> param = new HashMap<>();
	            param.put("scene", sceneStr);
	            param.put("page", "pages/index/index");
	            param.put("width", 430);
	            param.put("auto_color", false);
	            Map<String,Object> line_color = new HashMap<>();
	            line_color.put("r", 0);
	            line_color.put("g", 0);
	            line_color.put("b", 0);
	            param.put("line_color", line_color);
	          
	            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
	            HttpEntity requestEntity = new HttpEntity(param, headers);
	            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
	            System.out.println(entity.getBody()+"--------");
	            byte[] result = entity.getBody();
	           
	            inputStream = new ByteArrayInputStream(result);

	            File file = new File("D:\\bc\\h1.png");
	            if (!file.exists()){
	                file.createNewFile();
	            }
	            outputStream = new FileOutputStream(file);
	            int len = 0;
	            byte[] buf = new byte[1024];
	            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
	                outputStream.write(buf, 0, len);
	            }
	            outputStream.flush();
	        } catch (Exception e) {
	           
	        } finally {
	            if(inputStream != null){
	                try {
	                    inputStream.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	            if(outputStream != null){
	                try {
	                    outputStream.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	        return null;    
	    }


public static String replaceNameX(String str){
		String reg = ".{1}";
		StringBuffer sb = new StringBuffer();
		Pattern p = Pattern.compile(reg);
		Matcher m = p.matcher(str);
		int i = 0;
		while(m.find()){
			i++;
			if(i==1)
				continue;
			m.appendReplacement(sb, "*");
		}
		m.appendTail(sb);
		return sb.toString();

}
}
